import {Component, OnDestroy, OnInit, ViewEncapsulation} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {CrowdService} from "@crowd/crowd.service";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ValidationService} from "@shared/service/validator/validator.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import {Subscription} from "rxjs/Subscription";
import {Subject} from "rxjs/Subject";

@Component({
  selector: 'seed-step-1',
  templateUrl: './step-1.component.html',
  styleUrls: ['./step-1.component.scss', '../common.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class Step1Component implements OnInit, OnDestroy {
  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public subscription: Subscription = new Subscription();
  public step1Form: FormGroup;
  public fileImage = [];
  public activeType: any;
  public sportType: any;
  public startTime = '';
  public endTime = '';
  public endTimeCheck = false;
  public phoneCheck = true;
  public startNow = false;
  public params = {
    "activeDesc": "",
    "activeEndTime": 0,
    "activeName": "",
    "activeStartTime": 0,
    "activeType": '',
    "areaList": [
      {
        "address": "",
        "city": 0,
        "dist": 0,
        "latitude": 0,
        "longitude": 0,
        "province": 0
      }
    ],
    "contactWay": "",
    "crowdCode": "",
    "imgList": [],
    "remarks": "",
    "sportType": ''
  };
  public showPicker = false;  /* 有无选择地区*/
  constructor(
    public router: Router,
    public crowdService: CrowdService,
    private formbuilder: FormBuilder,
    public toolsServices: ToolsService,
    private route: ActivatedRoute
  ) {
    this.step1Form = this.formbuilder.group({
      activeType: ['', [Validators.required]],
      activeName: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]],
      sportType: ['', [Validators.required]],
      activeStartTime: ['', [Validators.required]],
      activeEndTime: ['', [Validators.required]],
      areaList: ['', [Validators.required]],
      contactWay: ['', [Validators.required, ValidationService.accountValidator]],
      activeDesc: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(1000)]],
      remarks: ['', [Validators.maxLength(100)]],
    });
    /**
     * @description 进入页面请求草稿信息，若有草稿信息，则显示草稿内容，同时给表单及保存参数赋值；
     * 若没有草稿信息，则显示placeholder
     * @author baoww765
     * @date 2017-12-25
     */
    this.route.queryParams.subscribe(param => {
      this.crowdService.getCrowdInfo(param['crowdCode'])
        .takeUntil(this.ngUnsubscribe).subscribe(res => {
        this.params.crowdCode = param['crowdCode'] ? param['crowdCode'] : '';
        if (res.result === '0' && res.data) {
          const oneReq = res.data.oneReq;
          for (const key in oneReq) {
            if (key === 'crowdCode' || key === 'imgList') {
              continue;
            }
            /*if (key === 'crowdCode') {
              continue;
            }
            if (key === 'imgList') {
              continue;
            }*/
            if (key === 'areaList') {
              if (oneReq.areaList.length === 0) {
                continue;
              } else {
                this.step1Form.controls[key].setValue(oneReq[key][0].address);
                const areaList = this.params.areaList[0];
                const oneReqData = oneReq[key][0];
                areaList.province = oneReqData.province;
                areaList.city = oneReqData.city;
                areaList.dist = oneReqData.dist;
                areaList.address = oneReqData.address;
                continue;
              }
            }
            this.params[key] = oneReq[key];
            this.step1Form.controls[key].setValue(oneReq[key]);
          }
          this.fileImage = oneReq.imgList && oneReq.imgList.length > 0 ? [...oneReq.imgList] : [];
          this.params.imgList = oneReq.imgList && oneReq.imgList.length > 0 ? [...oneReq.imgList] : [];
        }
      });
    });
  }

  ngOnInit() {
    this.getActiveType();
    this.getSportType();
  }

  /**
   * @description 选择活动类型
   * @author baoww765
   * @date 2017-11-11
   * @param event
   */
  selectActiveType(event) {
    this.params.activeType = event;
  }

  /**
   * @description 选择运动类型
   * @author baoww765
   * @date 2017-11-11
   * @param event
   */
  selectSportType(event) {
    this.params.sportType = event;
  }

  /**
   * @description 处理选择区域 获取所选区域信息并赋值
   * @author baoww765
   * @date 2017-11-11
   * @param event
   * */
  handleRegioPicker(event) {
    const area = this.params.areaList[0];
    area.province = event.provinceId;
    area.city = event.cityId;
    area.dist = event.districtId ? event.districtId : 0;
    area.address = event.provinceName + event.cityName + event.districtName;
    this.showPicker = false;
    this.step1Form.controls['areaList'].setValue(area.address);
  }

  /**
   * @desctiprtion 查询字典，获取活动类型
   * @author baoww765
   * @date 2017-11-08
   * */
  getActiveType() {
    this.crowdService.getActiveType().takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0') {
        this.activeType = res.data;
      }
    });
  }

  /**
   * @description 查询字典，获取运动类型
   * @author baoww765
   * @date 2017-11-11
   * */
  getSportType() {
    this.crowdService.getSportType().takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0') {
        this.sportType = res.data;
      }
    });
  };

  /**
   * @description 选择开始时间，失去焦点之后
   * @author baoww765
   * @date 2017-11-11
   * */
  startTimeCheck() {
    const nowTime = new Date().getTime();
    const paramStart = this.crowdService.dealTimeStamp(this.step1Form.controls['activeStartTime'].value);
    this.params.activeStartTime = paramStart;
    if (paramStart > nowTime) {
      this.startNow = false;
      if (this.step1Form.controls['activeStartTime'].value && this.step1Form.controls['activeEndTime'].value) {
        this.checkEndTime();
      }
    } else {
      this.startNow = true;
    }
  }

  /**
   * @description 选择结束时间，失去焦点之后
   * @author baoww765
   * @date 2017-11-15
   * */
  endTimeChecks() {
    if (this.step1Form.controls['activeStartTime'].value && this.step1Form.controls['activeEndTime'].value) {
      this.checkEndTime();
    }
  }

  /**
   * @description 处理时间格式，判断开始时间与结束时间，判断所选时间及当前时间
   * @author baoww765
   * @date 2017-11-11
   * */
  checkEndTime() {
    let startTimestamp;
    let endTimestamp;
    if (typeof(this.step1Form.controls['activeEndTime'].value) === 'string') {
      endTimestamp = this.crowdService.dealTimeStamp(this.step1Form.controls['activeEndTime'].value);
    } else {
      endTimestamp = this.step1Form.controls['activeEndTime'].value;
    }
    startTimestamp = this.params.activeStartTime;
    this.params.activeEndTime = endTimestamp;
    if (startTimestamp >= endTimestamp) {
      this.endTimeCheck = true;
    } else {
      this.endTimeCheck = false;
    }
  }

  /**
   * @description 填写联系方式
   * @author baoww765
   * @date 2017-11-11
   * */
  contactCheck() {
    if (!this.step1Form.controls['contactWay'].valid) {
      this.phoneCheck = false;
    } else {
      this.phoneCheck = true;
      this.params.contactWay = this.step1Form.controls['contactWay'].value;
    }
  }

  /**
   *@description 选择图片 上传图片 判断图片大小不超过5M，判断已有图片数量，最多可选图片不超过6张；
   * 选择完图片先上传到服务器，获取到图片所在服务器地址，然后存储到params 中，最后将此地址传输给后台
   * @author baoww765
   * @date 2017-11-11
   * @param event 所选图片
   */
  selectPicture(event) {
    const file = event.target.files;
    const that = this;
    let count = 0;
    for (const key in file) {
      count++;
      if (file[key].size >= 5242880) {
        this.toolsServices.showToast('图片大小不可大于5M！');
        return;
      }
      if (key === 'length' || (this.params.imgList.length + count) > 6) {
        return;
      }
     /* if (key === 'length') {
        return;
      }
      if ((this.params.imgList.length + count) > 6) {
        return;
      }*/
      this.crowdService.updateAvatar(file[key]).takeUntil(this.ngUnsubscribe).subscribe(res => {
        if (res.result === '0') {
          const reader = new FileReader();
          reader.readAsDataURL(file[key]);
          reader.onload = (e: any) => {
            if (that.fileImage.length >= 6) {
              return;
            }
            that.fileImage.push(e.target.result);
          };
          if (this.params.imgList.length < 6) {
            this.params.imgList.push(res.data[0]);
          }
        }
      });
    }
  }

  /**
   * @description 删除图片
   * @author baoww765
   * @date 2017-11-12
   * @param index
   * */
  deletePicture(index) {
    this.fileImage = [...this.fileImage.slice(0, index), ...this.fileImage.slice(index + 1)];
    this.params.imgList = [...this.params.imgList.slice(0, index), ...this.params.imgList.slice(index + 1)];
  }

  /**
   * @description 保存第一步,保存之前先判断活动开始时间与当前时间(有可能有草稿信息，直接下一步，或者重新编辑，重新发起);
   * 保存之前先赋值给参数对象params
   * @author baoww765
   * @date 2017-12-25
   * */
  saveOne() {
    this.params.activeDesc = this.step1Form.controls['activeDesc'].value;
    this.params.activeName = this.step1Form.controls['activeName'].value;
    this.params.remarks = this.step1Form.controls['remarks'].value;
    const nowTime = new Date().getTime();
    if (this.params.activeStartTime <= nowTime) {
      this.startNow = true;
    } else {
      this.crowdService.saveOne(this.params).takeUntil(this.ngUnsubscribe).subscribe(res => {
        if (res.result === '0') {
          this.router.navigate([`/crowd/step-2`], {
            queryParams: {
              crowdCode: res.data.crowdCode,
              activeStartTime: this.params.activeStartTime
            }
          });
        } else {
          this.toolsServices.showToast(res.msg);
        }
      });
    }
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}
